//
//  InviteFromViewController.swift
//  iModern
//
//  Created by Ralf on 5/25/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit
import AddressBook
import AddressBookUI
import MessageUI

class InviteFromViewController: UITableViewController, MFMessageComposeViewControllerDelegate
{
    var dataArray: NSArray!

    override func viewDidLoad()
    {

        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "InviteFromLocalContactsViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "sendMessage")
        self.dataArray = getSysContacts()
    }

    override func viewWillAppear(animated: Bool)
    {
        self.navigationItem.title = "邀请通讯录好友"

        let button
        = UIBarButtonItem(image: UIImage(named: "Back-Small.png")?.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "backButtonClick")

        self.navigationItem.leftBarButtonItem = button; }

    func backButtonClick()
    {
        self.navigationController?.popViewControllerAnimated(true)
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return 50
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let cell: InviteFromLocalContactsViewCell
        = (tableView.cellForRowAtIndexPath(indexPath) as? InviteFromLocalContactsViewCell)!
        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if self.canSendText()
        {
            let messageVC = self.configuredMessageComposeViewController(cell.TelLabel.text!)
            presentViewController(messageVC, animated: true, completion: nil)
        }
        else
        {

            //            TSMessage.showNotificationWithTitle:"提示"
            //            subtitle:"网络连接异常，请检查你的网络设置"
            //            type:TSMessageNotificationTypeError;
        }
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return self.dataArray.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell
                                     = tableView.dequeueReusableCellWithIdentifier("sendMessage", forIndexPath: indexPath) as! InviteFromLocalContactsViewCell
        let parameters: NSDictionary = self.dataArray.objectAtIndex(indexPath.row) as! NSDictionary
        cell.setData(parameters)
        return cell; }

    func getSysContacts() -> NSArray
    {
        var error:       Unmanaged<CFError>?
        var addressBook: ABAddressBookRef? = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()

        let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()

        if sysAddressBookStatus == .Denied || sysAddressBookStatus == .NotDetermined
        {
            // Need to ask for authorization
            var authorizedSingal: dispatch_semaphore_t = dispatch_semaphore_create(0)
            var askAuthorization: ABAddressBookRequestAccessCompletionHandler = {
                success, error in if success
                {
                    ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray
                    dispatch_semaphore_signal(authorizedSingal)
                }
            }
            ABAddressBookRequestAccessWithCompletion(addressBook, askAuthorization)
            dispatch_semaphore_wait(authorizedSingal, DISPATCH_TIME_FOREVER)
        }

        func analyzeSysContacts(sysContacts: NSArray) -> NSArray
        {
            var allContacts = NSMutableArray()

            func analyzeContactProperty(contact: ABRecordRef, property: ABPropertyID) -> [AnyObject]?
            {
                let propertyValues: ABMultiValueRef? = ABRecordCopyValue(contact, property)?.takeRetainedValue()
                if propertyValues != nil
                {
                    var values: Array<AnyObject> = Array()
                    for i in 0 ..< ABMultiValueGetCount(propertyValues)
                    {
                        let value = ABMultiValueCopyValueAtIndex(propertyValues, i)
                        switch property
                        {

                        case kABPersonSocialProfileProperty:
                            var valueDictionary: Dictionary = [String: String]()

                            let snsNSDict: NSMutableDictionary = value.takeRetainedValue() as! NSMutableDictionary

                            valueDictionary["_Username"] = snsNSDict.objectForKey(kABPersonSocialProfileUsernameKey) as? String

                            valueDictionary["_URL"] = snsNSDict.objectForKey(kABPersonSocialProfileURLKey) as? String

                            valueDictionary["_Serves"] = snsNSDict.objectForKey(kABPersonSocialProfileServiceKey) as? String
                            values.append(valueDictionary)
                            // IM
                        case kABPersonInstantMessageProperty:
                            var valueDictionary: Dictionary = [String: String]()

                            let imNSDict: NSMutableDictionary = value.takeRetainedValue() as! NSMutableDictionary

                            valueDictionary["_Serves"] = imNSDict.objectForKey(kABPersonInstantMessageServiceKey) as? String

                            valueDictionary["_Serves"] = imNSDict.objectForKey(kABPersonInstantMessageUsernameKey) as? String
                            values.append(valueDictionary)
                            // Date
                        case kABPersonDateProperty:
                            let date: String? = (value.takeRetainedValue() as? NSDate)?.description
                            if date != nil
                            {
                                values.append(date!)
                            }
                        default:
                            let val: String = (value.takeRetainedValue() as? String)!
                            values.append(val)
                        }
                    }
                    return values
                }
                else
                {
                    return nil
                }
            }

            for contact in sysContacts
            {
                let currentContact = NSMutableDictionary()
                /*
                部分单值属性
                */
                // 姓、姓氏拼音
                let FirstName      = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as! String
                let LastName       = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as! String

                // 姓名整理
                currentContact["fullName"] = LastName + FirstName

                // 电话
                let Phone: Array<AnyObject>? = analyzeContactProperty(contact, property: kABPersonPhoneProperty)
                if Phone != nil
                {
                    currentContact["Phone"] = Phone
                }

                allContacts.addObject(currentContact)
            }
            return allContacts
        }

        return analyzeSysContacts(ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray)
    }

    func canSendText() -> Bool
    {
        return MFMessageComposeViewController.canSendText()
    }

    func configuredMessageComposeViewController(phone: NSString) -> MFMessageComposeViewController
    {
        let messageComposeVC = MFMessageComposeViewController()
        messageComposeVC.recipients = NSArray(object: phone) as? [String]
        messageComposeVC.messageComposeDelegate = self
        messageComposeVC.body = "HI!iModern爱魔登很不错，邀你共享iModern爱魔登 -来自我的邀请"
        return messageComposeVC

    }

    func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult)
    {
        controller.dismissViewControllerAnimated(true, completion: nil)
    }

}
